<script>
import Explain from "./explain.vue"
import request from "../../../utils/request"
import ChineseEnglishExchange from "./chineseEnglishExchange.vue"
import settings from "./settings.vue"
import vocabularyCollection from "../../../components/vocabularyCollection.vue"
import persistence from "@/store/persistence"

export default {
  name: "main",
  components: {
    ChineseEnglishExchange,
    Explain,
    settings,
    vocabularyCollection,
  },
  data() {
    return {
      showExplain: false,
      userLastAnswer: true, //用户回答是否正确
      wordPracticeComponentInstance: null, //单词练习组件实例
      hasShowExplain: false, // 是否已经展示过解释
    }
  },
  computed: {
    currentWordItem() {
      return this.wordList[this.currentIndex]
    },
  },
  props: {
    thesaurusId: {
      type: String,
      default: "",
    },
    practiceMode: {
      type: String,
      default: "",
    },
    height: {
      type: String,
      default: "auto",
    },
    //是否显示上一个按钮
    showPrevBtn: {
      type: Boolean,
      default: true,
    },
    currentIndex: {
      type: Number,
      default: 0,
    },
    wordList: {
      type: Array,
      default: [],
    },
  },
  emits: ["nextWord", "submitRecord", "prevWord"],
  watch: {
    currentIndex: {
      handler(val) {
        this.$nextTick(() => {
          this.autoAudio()
          //获取下一个单词的选项列表
          this.getOptionList()
        })
      },
      immediate: true,
    },
  },
  methods: {
    //单词读音自动播放
    autoAudio() {
      if (this.wordPracticeComponentInstance && !this.showExplain) {
        //自动播放音频
        if (persistence.getters.getAutoAudioSetting()) {
          this.wordPracticeComponentInstance.playAudio && this.wordPracticeComponentInstance.playAudio()
        }
      }
    },
    //下一个单词
    nextWord() {
      this.showExplain = false
      this.$emit("nextWord")
    },
    //上一个单词
    prevWord() {
      this.showExplain = false
      this.$emit("prevWord")
    },
    //选中了选项
    handleSelect(userAnswer) {
      setTimeout(() => {
        //回答正确
        if (userAnswer === true) {
          //之前回答错了且没有弹过解释则弹出解释
          if (this.userLastAnswer === false && !this.hasShowExplain) {
            this.$emit("submitRecord", this.userLastAnswer)
            this.showExplain = true
            //没有回答错误则直接跳转到下一个单词
          } else {
            this.$emit("nextWord", this.userLastAnswer)
            // 重置状态
            this.userLastAnswer = true
            this.hasShowExplain = false
          }
        }
        this.userLastAnswer = userAnswer
      }, 1000)
    },
    //显示注释
    viewExplain() {
      this.userLastAnswer = false
      this.hasShowExplain = true
      this.showExplain = true
    },
    //获取该单词的选项（从别的题随机抽）
    async getOptionList() {
      //从单词列表 内随机抽取三个单词作为选项
      let optionList = await request({
        url: "userWordsRecord/getRandWordList",
        data: {
          wordId: this.currentWordItem.wordId,
          thesaurusId: this.thesaurusId,
        },
        showLoading: true,
        errorHandle: true,
      })
      //将自身插入选项列表中，且插入的位置随机
      optionList.push(this.currentWordItem)
      optionList.sort(() => {
        return Math.random() - 0.5
      })
      // 将选项列表传递给子组件
      this.wordPracticeComponentInstance &&
        this.wordPracticeComponentInstance.setOptionList &&
        this.wordPracticeComponentInstance.setOptionList(optionList)
    },
    //再练一次
    handleRePractice() {
      this.showExplain = false
      this.$nextTick(() => {
        this.autoAudio()
        this.getOptionList()
      })
    },
  },
  provide() {
    return {
      root: this,
    }
  },
}
</script>

<template>
  <view class="component" :style="'height:' + height">
    <view class="content">
      <!--			单词收藏-->
      <view class="vocabularyCollection">
        <vocabularyCollection
          :word-info="currentWordItem"
          @collection="(val) => (wordList[currentIndex].existFavorite = val)"
        ></vocabularyCollection>
      </view>
      <!--				单词解释查看-->
      <explain v-if="showExplain" :word-id="currentWordItem.wordId"></explain>
      <!--			单词练习-->
      <div v-else>
        <!--		中英文互译-->
        <chinese-english-exchange
          v-if="['中考英', '英考中'].includes(practiceMode)"
          :wordInfo="currentWordItem"
          :type="practiceMode"
          @select="handleSelect"
        ></chinese-english-exchange>
      </div>
      <view class="footer">
        <!--			上一个/下一个/查看注释-->
        <view class="control-btn">
          <!--				上一个-->
          <text class="side-btn" @click="prevWord" v-if="showPrevBtn && currentIndex !== 0">{{ "<" }}上一个</text>
          <!--				占位-->
          <text v-else style="width: 114rpx"></text>
          <!--			不认识按钮，直接弹出注释-->
          <view class="unknown-btn" @click="viewExplain" v-if="!showExplain">查看释义 </view>
          <!--				切回到练习模式-->
          <view class="unknown-btn" @click="handleRePractice" v-else>再练一次</view>
          <!--				下一个（只有查看释义时才展示）-->
          <text class="side-btn" @click="nextWord" v-if="showExplain">下一个{{ ">" }}</text>
          <!--				占位-->
          <text v-else style="width: 114rpx"></text>
        </view>
				<!--		设置-->
				<view class="setting">
					<settings
						:currentWordItem="currentWordItem"
					></settings>
				</view>
			</view>
      <slot></slot>
    </view>
  </view>
</template>

<style scoped lang="scss">
.component {
  overflow: auto;
  padding-bottom: 20vh;
  .content {
    position: relative;
    .vocabularyCollection {
      position: absolute;
      top: 2vh;
      right: 5vh;
    }
		> .footer {
			position: fixed;
			left: 0;
			bottom: 0;
			width: 100%;
			background: white;
			padding: {
				top: 10rpx;
				bottom: calc(10rpx + env(safe-area-inset-bottom));
			}
			> .control-btn {
				display: flex;
				justify-content: space-around;
				align-items: center;
				font-size: 30rpx;
				.unknown-btn {
					width: 40%;
					height: 70rpx;
					line-height: 70rpx;
					text-align: center;
					border-radius: 50rpx;
					border: 2rpx solid var(--theme-color);
					background: var(--theme-color-light);
					color: var(--text-color);
				}
				.side-btn {
					color: var(--text-color-light);
				}
			}
			> .setting {
				margin-top: 40rpx;
			}
		}
  }
}
</style>
